package com.corpgovernment.organization.controller.post;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.corpgovernment.api.operatelog.chooseconstant.ChooseBusinesstype;
import com.corpgovernment.api.organization.model.enums.WholeGroupQueryEnum;
import com.corpgovernment.api.organization.model.org.GetOrgTreeResponse;
import com.corpgovernment.api.organization.model.org.GetPositionResponse;
import com.corpgovernment.api.organization.model.post.*;
import com.corpgovernment.api.organization.model.post.front.*;
import com.corpgovernment.api.travelstandard.vo.TravelStandardPostVo;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.common.operatelog.OperateLog;
import com.corpgovernment.common.utils.Null;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbPostInfo;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.enumm.PositionOperationEnum;
import com.corpgovernment.organization.mapper.MbUserOrgRelationMapper;
import com.corpgovernment.organization.model.SyncPositionInfoModel;
import com.corpgovernment.organization.service.*;
import com.corpgovernment.organization.util.OrganizationUtil;
import com.corpgovernment.travelstandard.entity.db.TravelStandardPost;
import com.corpgovernment.travelstandard.impl.TravelStandardPostService;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.corpgovernment.permission.config.PermissionFilter.DATA_PERMISSION_ORG_ID_LIST;

/**
 * 岗位controller
 *
 * @author wangyujue
 */
@RestController
@Slf4j
@RequestMapping("/post")
public class PostController {

    @Autowired
    private IPostService postService;
    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private IUserOrgRelationService userOrgRelationService;
    @Autowired
    private TravelStandardPostService travelStandardPostService;
    @Autowired
    private PositionInfoService positionInfoService;
    @Autowired
    private OrganizationApollo organizationApollo;
    @Autowired
    private MbUserOrgRelationMapper mbUserOrgRelationMapper;
    private static final int LENGTH_LIMIT = 20;

    /**
     * 查询岗位列表-运营端职级模块 前端接口
     *
     * @return JSONResult
     */
    @ApiOperation("查询职级接口")
    @RequestMapping("/getPositionList")
    public JSONResult<List<CompanyPositionListVo>> getPositionList(@RequestBody GetPositionListRequest getPositionListRequest) {
        String orgId = getPositionListRequest.getId();
        if (StringUtils.isBlank(orgId)) {
            orgId = "zjiXyTVVmY";
        }
        List<MbOrgInfo> mbOrgInfoList = new ArrayList<>();
        // 查询全集团数据
        MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
        if (Objects.isNull(mbOrgInfo)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "子公司信息不存在");
        }
        mbOrgInfoList.add(mbOrgInfo);
        log.info("查询到的组织结构为：{}", JsonUtils.toJsonString(mbOrgInfoList));
        if (CollectionUtil.isEmpty(mbOrgInfoList)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "子公司信息不存在");
        }
        // 数据权限管控
        List<String> accessibleOrgIdList = getAccessibleOrgIdList();
        if (CollectionUtils.isNotEmpty(accessibleOrgIdList)) {
            mbOrgInfoList = mbOrgInfoList.stream().filter(m -> accessibleOrgIdList.contains(m.getOrgId()))
                    .collect(Collectors.toList());
            log.info("数据权限筛选后的组织结构为：{}", JsonUtils.toJsonString(mbOrgInfoList));
        }


        List<CompanyPositionListVo> returnList = new ArrayList<>();
        this.getCompanyPositionListVo(mbOrgInfoList, returnList);
        return JSONResult.success(returnList);
    }
    @ApiOperation("查询职级接口包括子公司")
    @RequestMapping("/getPositionListIncludingSubsidiaries")
    public JSONResult<List<GetPositionResponse>> getPositionListIncludingSubsidiaries(@RequestBody GetPositionListRequest getPositionListRequest) {
        String orgId = getPositionListRequest.getId();
        // 查询所有组织结构
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
        // 是否开启全集团查询 true:查询全集团数据, false:查询公司数据
        boolean findWholeGroup = WholeGroupQueryEnum.APPROVE.getCode().equals(getPositionListRequest.getWholeGroupQuery())
                && organizationApollo.enableApproveShowAllOrg();
        List<GetOrgTreeResponse> getOrgTreeResponses;
        if(findWholeGroup){
            getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, null, true);
        } else {
            getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, orgId, true);
        }
        List<GetPositionResponse> positionTree = JsonUtils.parseArray(JsonUtils.toJsonString(getOrgTreeResponses),GetPositionResponse.class);

        // 查询所有职级
        List<CompanyPositionListVo> returnList = new ArrayList<>();
        List<Long> oIds = extractOIds(getOrgTreeResponses);
        List<MbOrgInfo> mbOrgInfoListFilter = mbOrgInfoList.stream().filter(mbOrgInfo -> oIds.contains(mbOrgInfo.getId())).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(mbOrgInfoList)){
            return JSONResult.success(null);
        }
        this.getCompanyPositionListVo(mbOrgInfoListFilter, returnList,mbOrgInfoList);
        Map<String,CompanyPositionListVo> companyPositionMap =  returnList.stream().collect(Collectors.toMap(CompanyPositionListVo::getId, Function.identity()));

        // 构造返回数据
        this.buildGetPositionResponse(positionTree,companyPositionMap);

        return JSONResult.success(positionTree);
    }

    /**
     * 从给定的GetOrgTreeResponse列表中提取所有oId，并返回其列表。
     *
     * @param getOrgTreeResponses 包含GetOrgTreeResponse对象的列表
     * @return 包含所有oId的Long类型列表
     */
    public static List<Long> extractOIds(List<GetOrgTreeResponse> getOrgTreeResponses) {
        List<Long> oIds = new ArrayList<>();
        for (GetOrgTreeResponse response : getOrgTreeResponses) {
            oIds.add(response.getOId());
            if (response.getChildren() != null) {
                oIds.addAll(extractOIds(response.getChildren())); // 递归处理子节点
            }
        }
        return oIds;
    }

    public void buildGetPositionResponse(List<GetPositionResponse> positionTree,Map<String,CompanyPositionListVo> companyPositionMap){
        for (GetPositionResponse getPositionResponse : positionTree) {
            getPositionResponse.setPostList(companyPositionMap.get(getPositionResponse.getOrgId()).getChildren());
            List<GetPositionResponse> children = getPositionResponse.getChildren();
            if(CollectionUtil.isNotEmpty(children)){
                this.buildGetPositionResponse(children,companyPositionMap);
            }
        }
    }
    private List<String> getAccessibleOrgIdList() {
        // 数据权限管控
        Object orgIds = RequestContext.getCurrentContext().getContextParams(DATA_PERMISSION_ORG_ID_LIST);
        List<String> listOrgIds = new ArrayList<>();
        if (Objects.nonNull(orgIds)) {
            String str = JsonUtils.toJsonString(orgIds);
            if (StringUtils.isNotBlank(str)) {
                log.info("获取到的数据权限为：{}", str);
                listOrgIds = JsonUtils.parseArray(str, String.class);
            }
        }
        return listOrgIds;
    }

    private void getCompanyPositionListVo(List<MbOrgInfo> mbOrgInfoList, List<CompanyPositionListVo> returnList) {
        for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
            List<MbPostInfo> mbPostInfos = postService.listByOrgId(mbOrgInfo.getOrgId());
            companyPositionListVo(returnList, mbOrgInfo, mbPostInfos);
        }
    }

    private void getCompanyPositionListVo(List<MbOrgInfo> mbOrgInfoList, List<CompanyPositionListVo> returnList, List<MbOrgInfo> allMbOrgInfoList) {
        for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
            List<MbPostInfo> mbPostInfos = postService.listByOrgId(mbOrgInfo.getOrgId(),allMbOrgInfoList);
            companyPositionListVo(returnList, mbOrgInfo, mbPostInfos);
        }
    }

    private void companyPositionListVo(List<CompanyPositionListVo> returnList, MbOrgInfo mbOrgInfo, List<MbPostInfo> mbPostInfos) {
        List<PostListVo> postList = new ArrayList<>();
        List<Long> postIds = mbPostInfos.stream().map(MbPostInfo::getId).collect(Collectors.toList());
        List<Map<Long, Long>>  postIdMaps = mbUserOrgRelationMapper.groupByPostId(postIds);
        // 合并所有Map
        Map<Long, Long> mergedMap = postIdMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("postId"), // 提取postId作为键
                        map -> map.get("count"),  // 提取count作为值
                        (oldValue, newValue) -> oldValue // 如果有重复的postId，保留旧值
                ));
        for (MbPostInfo mbPostInfo : mbPostInfos) {
            PostListVo postListVo = new PostListVo();
            postListVo.setId(mbPostInfo.getId());
            postListVo.setLabel(mbPostInfo.getName());
            if (mbPostInfo.getAllowance() != null){
                postListVo.setAllowance(mbPostInfo.getAllowance().setScale(2, RoundingMode.HALF_UP).toString());
            }
            postListVo.setRights(mbPostInfo.getRights());
            postListVo.setRankNo(mbPostInfo.getCode());
            if(ObjectUtil.isNotEmpty(mergedMap) && ObjectUtil.isNotEmpty(mergedMap.get(mbPostInfo.getId()))){
                postListVo.setCount(Math.toIntExact(mergedMap.get(mbPostInfo.getId())));
            }
            postList.add(postListVo);
        }
        CompanyPositionListVo companyPositionListVo = new CompanyPositionListVo();
        companyPositionListVo.setId(mbOrgInfo.getOrgId());
        companyPositionListVo.setLabel(mbOrgInfo.getName());
        companyPositionListVo.setType(mbOrgInfo.getOrgType());
        companyPositionListVo.setChildren(postList);
        companyPositionListVo.setId(mbOrgInfo.getOrgId());
        companyPositionListVo.setLabel(mbOrgInfo.getName());
        companyPositionListVo.setType(mbOrgInfo.getOrgType());
        returnList.add(companyPositionListVo);
    }

    /**
     * 查询岗位列表-人员设置模块
     * 前端接口
     *
     * @return JSONResult
     */
    @RequestMapping("/getPositionListToPostVo")
    public JSONResult getPositionListToPostVo(@RequestBody GetPositionListRequest getPositionListRequest) {
        String orgId = getPositionListRequest.getId();
        if (StringUtils.isBlank(orgId)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_ID_NULL);
        }
        String orgType = getPositionListRequest.getOrgType();
        if (StringUtils.isBlank(orgType)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_TYPE_IS_NULL);
        }
        //假如是部门类型的组织id，则寻找距离该部门最近的公司
        if (OrgTypeEnum.D.getCode().equals(orgType)){
            MbOrgInfo orgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
            if (orgInfo == null){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PARENT_ORG_IS_NULL);
            }
            orgId = orgInfo.getOrgId();
        }
        List<PostVo> returnList = new ArrayList<>();
        // 查询岗位列表
        List<MbPostInfo> mbPostInfos = postService.listByOrgId(orgId);
        for (MbPostInfo mbPostInfo : mbPostInfos) {
            PostVo postVo = new PostVo();
            postVo.setId(mbPostInfo.getId());
            postVo.setOrgId(mbPostInfo.getOrgId());
            postVo.setName(mbPostInfo.getName());
            returnList.add(postVo);
        }
        return JSONResult.success(returnList);
    }

    /**
     * 编辑岗位
     * 前端接口
     * 契约文档：http://10.5.119.87:9526/project/11/interface/api/573
     * url：http://localhost:7890/post/posEdit?posEdit=1&id=&postId=&name=
     *
     * @param postEditRequest
     * @return
     */

    @OperateLog(ChooseBusinesstype.CONFIGPOSITION)
    @ApiOperation("新增/修改/删除职级接口")
    @PostMapping("/posEdit")
    public JSONResult<PostEditResponse> posEdit(@RequestBody PostEditRequest postEditRequest) {
        Integer status = postEditRequest.getStatus();
        if (status == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "status");
        }
        if (Integer.valueOf(status) > PositionOperationEnum.DELETE.getCode()
                || Integer.valueOf(status) < PositionOperationEnum.ADD.getCode()) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_TYPE_ERROR);
        }
        String name = postEditRequest.getName();
        String rights = postEditRequest.getRights();
        Long postId = postEditRequest.getId();
        String orgId = postEditRequest.getPid();
        String rankNo = postEditRequest.getRankNo();
        BigDecimal allowance = null;
        if (status == PositionOperationEnum.MODIFY.getCode() || status == PositionOperationEnum.ADD.getCode()){
            if (!StringUtils.isBlank(postEditRequest.getAllowance())){
                try {
                    allowance = new BigDecimal(postEditRequest.getAllowance());
                    if (allowance.compareTo(BigDecimal.ZERO) < 0){
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.ALLOWANCE_LESS_ZERO);
                    }
                    BigDecimal maxNumber = new BigDecimal(99999999);
                    if (allowance.compareTo(maxNumber) > 0){
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.ALLOWANCE_OUT_LIMIT);
                    }
                }
                catch (NumberFormatException e){
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_TYPE_ERROR);
                }
            }
            if (status.equals(PositionOperationEnum.MODIFY.getCode()) || status.equals(PositionOperationEnum.DELETE.getCode())) {
                if (postId == null) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "postId");
                }
            }
            if (StringUtils.isBlank(name)){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "name");
            }
            if (name.length() > 50){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.RANK_NAME_LENGTH);
            }
        }
        // 新增
        if (status == PositionOperationEnum.ADD.getCode()) {
            // 校验名字是否重复
            MbPostInfo dbInfo = postService.findByNameAndOrgId(name, orgId);
            if (dbInfo != null && StringUtils.isNotBlank(dbInfo.getOrgId())) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.RANK_NAME_EXISTS);
            }
            MbPostInfo mbPostInfo = new MbPostInfo();
            mbPostInfo.setName(name);
            mbPostInfo.setRights(rights);
            mbPostInfo.setOrgId(orgId);
            mbPostInfo.setAllowance(allowance);
            mbPostInfo.setCode(rankNo);
            postService.save(mbPostInfo);
            PostEditResponse postEditResponse = new PostEditResponse();
            PostEditVo postEditVo = new PostEditVo();
            postEditVo.setId(mbPostInfo.getId());
            postEditVo.setLabel(name);
            if (mbPostInfo.getAllowance() != null){
                postEditVo.setAllowance(mbPostInfo.getAllowance().setScale(2, RoundingMode.HALF_UP).toString());
            }
            postEditVo.setRights(rights);
            postEditResponse.setAddPosInfo(postEditVo);
            return new JSONResult(postEditResponse);
        }
        // 编辑
        if (status == 1) {
            // 先查找之前的数据，然后对比db
            MbPostInfo postInfo = postService.find(postId);
            List<MbPostInfo> postInfoList = postService.findByName(name);
            for (MbPostInfo mbPostInfo : postInfoList) {
                if (mbPostInfo != null &&  StringUtils.isNotBlank(mbPostInfo.getName())) {
                    if (mbPostInfo.getName().equals(postEditRequest.getName()) && !mbPostInfo.getId().equals(postId) && mbPostInfo.getOrgId().equals(postInfo.getOrgId())) {
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.RANK_NAME_EXISTS);
                    }
                }
            }
            MbPostInfo mbPostInfo = new MbPostInfo();
            mbPostInfo.setId(postId);
            mbPostInfo.setName(name);
            mbPostInfo.setRights(rights);
            mbPostInfo.setAllowance(allowance);
            mbPostInfo.setCode(rankNo);
            boolean i = postService.update(mbPostInfo);
            return new JSONResult(i);
        }
        // 删除
        if (status == PositionOperationEnum.DELETE.getCode()) {
            // 判断差标
            TravelStandardPostVo travelStandardPostVo = new TravelStandardPostVo();
            travelStandardPostVo.setPostid(postId);
            //向差标模块查询是否职位是否已关联差标
            List<TravelStandardPost> travelStandardPostList = travelStandardPostService.list(travelStandardPostVo);
            if (!CollectionUtils.isEmpty(travelStandardPostList)) {
                return JSONResult.errorMsg("职级绑定了差标，不能删除！");
            }
            boolean i = postService.deletePostAndRelationById(postId);
            return new JSONResult(i);
        }
        return JSONResult.ok();
    }

    /**
     * 前端批量修改雇员的岗位
     * 契约文档：http://10.5.119.87:9526/project/252/interface/api/6327
     * @return JSONResult
     */
    @RequestMapping("/frontBatchUpdateEmployeePost")
    public JSONResult frontBatchUpdateEmployeePost(@RequestBody PostBatchUpdateRequest postBatchUpdateRequest) {
        if (StringUtils.isBlank(postBatchUpdateRequest.getOrgId())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "orgId");
        }
        if (StringUtils.isBlank(postBatchUpdateRequest.getPostId())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "postId");
        }
        if (postBatchUpdateRequest.getUids()== null || postBatchUpdateRequest.getUids().size()==0){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_INFO_DONT_EXISTS);
        }
        // 批量更新岗位
        boolean flagA = organizationEmployeeService.frontBatchUpdateEmployeePost(postBatchUpdateRequest.getUids(), Long.valueOf(postBatchUpdateRequest.getPostId()),postBatchUpdateRequest.getOrgId());
        if (!flagA) {
            return JSONResult.errorMsg("给员工分配职级失败");
        }

        return JSONResult.ok();
    }

    /**
     * 同步职级接口
     */
    @ApiOperation("对外新增/修改/删除职级接口")
    @PostMapping("/syncPositionInfo")
    public JSONResult<Object> syncPositionInfo(@RequestBody SyncPositionInfoRequest syncPositionInfoRequest) {
        // 校验参数
        checkParams(syncPositionInfoRequest);
        String corpCode = syncPositionInfoRequest.getCorpCode();
        List<PositionInfoDTO> positionList = syncPositionInfoRequest.getPositionList();

        List<SyncPositionInfoModel> syncPositionInfoModelList = positionList.stream().map(positionInfo -> {
            SyncPositionInfoModel model = new SyncPositionInfoModel();
            model.setPositionName(positionInfo.getPositionName());
            model.setOperationType(positionInfo.getOperationType());
            model.setPositionCode(positionInfo.getPositionCode());
            return model;
        }).collect(Collectors.toList());
        positionInfoService.syncPositionInfo(syncPositionInfoModelList, corpCode);
        return JSONResult.ok();
    }


    private  void checkParams(SyncPositionInfoRequest syncPositionInfoRequest) {
        if (syncPositionInfoRequest == null){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.REQUEST_EMPTY);
        }
        if (StringUtils.isBlank(syncPositionInfoRequest.getCorpCode())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.COMPANY_CODE_CAN_NOT_BE_NULL);
        }
        if (CollectionUtils.isEmpty(syncPositionInfoRequest.getPositionList())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.POSITION_CONTENT_CAN_NOT_BE_NULL);
        }
        syncPositionInfoRequest.getPositionList().forEach(t->{
            if (t.getOperationType() == null || StringUtils.isBlank(t.getPositionName())){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.POSITION_PARAM_CANNOT_BE_NULL);
            }
            if (Null.or(t.getPositionCode(), code -> code.length() >= LENGTH_LIMIT, false) || t.getPositionName().length() >= LENGTH_LIMIT){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.POSITION_PARAM_LENGTH_TOO_LONG);
            }
        });
    }


    /**
     * 查询岗位列表
     * @return JSONResult
     */
    @RequestMapping("/fronListPostByOrgId")
    @ResponseBody
    public JSONResult<List<PostVo>> fronListPostByOrgId(@RequestBody FronListPostByOrgIdRequest fronListPostByOrgIdRequest) {
        String orgId = fronListPostByOrgIdRequest.getOrgId();
        if (StringUtils.isBlank(orgId)){
            return JSONResult.success(null);
        }
        MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
        if (mbOrgInfo == null){
            return null;
        }
        orgId = mbOrgInfo.getOrgId();
        List<PostVo> returnList = new ArrayList<>();
        // 查询岗位列表
        List<MbPostInfo> mbPostInfos = postService.listByOrgId(orgId);
        for (MbPostInfo mbPostInfo : mbPostInfos) {
            PostVo postVo = new PostVo();
            postVo.setId(mbPostInfo.getId());
            postVo.setOrgId(mbPostInfo.getOrgId());
            postVo.setName(mbPostInfo.getName());
            returnList.add(postVo);
        }
        return JSONResult.success(returnList);
    }

////////////////////////////////////////////////////////////////////////////


    /**
     * 查询岗位列表
     * 后端接口
     * url：http://localhost:7890/post/listPostByOrgId?orgId=1
     *
     * @param orgId 组织结构id
     * @return JSONResult
     */
    @RequestMapping("/listPostByOrgId")
    @ResponseBody
    public JSONResult<List<PostVo>> listPostByOrgId(@RequestParam("orgId") String orgId) {
        return JSONResult.success(postService.listPostByOrgId(orgId));
    }

    /**
     * 查询岗位列表
     * 后端接口
     * url：http://localhost:7890/post/listPostByOrgId?orgId=1
     *
     * @param orgIdList 组织结构id
     * @return JSONResult
     */
    @RequestMapping("/listPostByOrgIdList")
    @ResponseBody
    public JSONResult<List<PostVo>> listPostByOrgIdList(@RequestParam("orgIdList") List<String> orgIdList) {
        List<PostVo> returnList = new ArrayList<>();
        // 查询岗位列表
        List<MbPostInfo> mbPostInfos = postService.listByOrgIds(orgIdList);
        for (MbPostInfo mbPostInfo : mbPostInfos) {
            PostVo postVo = new PostVo();
            postVo.setId(mbPostInfo.getId());
            postVo.setOrgId(mbPostInfo.getOrgId());
            postVo.setName(mbPostInfo.getName());
            returnList.add(postVo);
        }
        return JSONResult.success(returnList);
    }

    /**
     * 根据组织id和uId查询某个人岗位
     * 后端接口
     * url：
     * @param orgId 组织结构id
     * @param uId 用户id
     * @return JSONResult
     */
    @RequestMapping("/listPostByOrgIdAndUId")
    @ResponseBody
    public JSONResult<PostVo> listPostByOrgIdAndUId(String orgId,String uId) {
        return JSONResult.success(postService.listPostByUidAndOrgId(uId, orgId));
    }

    /**
     * 根据岗位id查询岗位信息
     *
     * @param postIds
     * @return
     */
    @RequestMapping("/listByPostIds")
    public JSONResult<List<PostVo>> listByPostIds(@RequestBody List<Long> postIds) {
        if (CollectionUtils.isEmpty(postIds)) {
            return JSONResult.errorMsg("postIds不能为空");
        }
        List<MbPostInfo> postInfoList = postService.listByPostIds(postIds);
        List<PostVo> result = postInfoList.stream().filter(Objects::nonNull).map(e -> {
            PostVo postVo = new PostVo();
            postVo.setId(e.getId());
            postVo.setName(e.getName());
            postVo.setOrgId(e.getOrgId());
            return postVo;
        }).collect(Collectors.toList());
        return JSONResult.success(result);
    }

//    /**
//     * 批量修改用户的岗位
//     *
//     * @return JSONResult
//     */
//    @RequestMapping("/batchUpdateEmployeePost")
//    @Transactional
//    public JSONResult batchUpdateEmployeePost(Long postId, List<String> uidList) {
//        // 先将postId原来所有人的postId置为空
//        boolean flag = organizationEmployeeService.clearPostEmployeeByPostId(postId);
//        if (!flag) {
//            return JSONResult.errorMsg("清空员工职级失败");
//        }
//        // 然后再将uidList用户的postId更新为当前postId
//        boolean flagA = organizationEmployeeService.batchUpdateEmployeePost(uidList, postId);
//        if (!flagA) {
//            return JSONResult.errorMsg("给员工分配职级失败");
//        }
//        return JSONResult.ok();
//    }


    /**
     * 保存或更新岗位
     *
     * @param postVo 岗位信息
     * @return 成功还是失败
     */
    @PostMapping("/saveOrUpdatePost")
    public JSONResult savePost(PostVo postVo) {
        // 编辑逻辑
        if (postVo.getId() != null) {
            MbPostInfo mbPostInfo = new MbPostInfo();
            BeanUtils.copyProperties(postVo, mbPostInfo);
            boolean update = postService.update(mbPostInfo);
            if (!update) {
                JSONResult.errorMsg("修改失败");
            }
            return JSONResult.ok();
        }
        // 新增逻辑
        MbPostInfo mbPostInfo = new MbPostInfo();
        BeanUtils.copyProperties(postVo, mbPostInfo);
        boolean flag = postService.save(mbPostInfo);
        if (!flag) {
            JSONResult.errorMsg("插入失败");
        }
        return JSONResult.ok();
    }

    @PostMapping("/getPositionListOrMan")
    public JSONResult getPositionListOrMan(@RequestBody GetPositionListOrManRequest request) {

        String orgId = request.getOrgId();
        List<GetPositionListOrManResponse> responses = new ArrayList<>();

        if (StringUtils.isBlank(request.getQuery())) {
            return JSONResult.success(responses);
        }

        List<String> orgIds = organizationInfoService.listAllDepartmentByOrgId(orgId);


        //职级模糊匹配
        List<MbPostInfo> mbPostInfos = postService.findByLikeName(orgIds, request.getQuery());
        if (!CollectionUtils.isEmpty(mbPostInfos)) {
            mbPostInfos.stream().forEach(a -> {
                responses.add(new GetPositionListOrManResponse(a.getId().toString(), a.getName(), "1"));
            });
        }
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.findLikeName(orgIds, request.getQuery());
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(a -> {
                responses.add(new GetPositionListOrManResponse(a.getUid(), a.getName(), "2"));
            });
        }
        return JSONResult.success(responses);
    }

    /**
     * 查询数据权限内所有岗位列表
     * @return JSONResult
     */
    @PostMapping("/listPostByCondition")
    public JSONResult<ListPostByConditionResponse> listPostByCondition(@RequestBody ListPostByConditionRequest request, BaseUserInfo baseUserInfo) {
        return JSONResult.success(postService.listPostByCondition(request, baseUserInfo));
    }

}
